#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

/*
 * 线程间的互斥
 * 1. 强调排他性访问，这里没有严格的顺序(reverseMsg 与 printfMsg函数任意执行，但内部的代码是原子性)
 * 2. 打印结果 要么是123456789 要么是987654321

buf : 123456789
buf : 987654321
buf : 987654321
buf : 987654321
buf : 987654321
buf : 123456789
buf : 123456789

*/

#define N 64

typedef struct message {
	char buf[N];
	int len;
}msg_t;

//定义互斥锁
pthread_mutex_t gmutex;

void * reverseMsg(void *);
void * printfMsg(void *);

int main(int argc, char * argv[]){
	msg_t msg = {"123456789", 9};
	pthread_t tid[2];

	pthread_mutex_init(&gmutex, NULL);
	pthread_create(&tid[0], NULL, reverseMsg, (void *)&msg);
	pthread_create(&tid[1], NULL, printfMsg, (void *)&msg);
	
	pthread_join(tid[0], NULL);
	pthread_join(tid[1], NULL);

	return 0;
}

//反转字符串
void * reverseMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	int i = 0;
	char tmpChar;

	while(1){
		pthread_mutex_lock(&gmutex);
		for(i = 0 ; i < msg->len / 2 ; i++){
			tmpChar = msg->buf[i];
			msg->buf[i] = msg->buf[msg->len - i - 1];
			msg->buf[msg->len - i - 1] = tmpChar;
		}
		pthread_mutex_unlock(&gmutex);
	}
	return NULL;
}

//打印字符串
void * printfMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	while(1){
		pthread_mutex_lock(&gmutex);
		printf("buf : %s\n", msg->buf);
		pthread_mutex_unlock(&gmutex);
		sleep(1);
	}

	return NULL;
}
